package test

import (
	"fmt"
	"sync"
	"time"
)

//test for WaitGroup
func WaitGroup() {
	wg := sync.WaitGroup{}
	for i := 0; i < 10; i++ {
		wg.Add(1)
		var str = "xxx"
		go func(i int, str string) {
			sendRPC(i, str)
			wg.Done()
		}(i, str)
	}
	wg.Wait()
	fmt.Println("down")
}

func sendRPC(i int, str string) {
	fmt.Printf("%d -- %s\n", i, str)
}

func Bank() {
	alice := 10000
	bob := 10000
	var mu = sync.Mutex{}
	total := alice + bob
	go func() {
		for i := 0; i < 1000; i++ {
			mu.Lock()
			alice -= 1
			//	mu.Unlock()
			//	mu.Lock()
			bob += 1
			mu.Unlock()
		}
	}()

	go func() {
		for i := 0; i < 1000; i++ {
			mu.Lock()
			bob -= 1
			//	mu.Unlock()
			//	mu.Lock()
			alice += 1
			mu.Unlock()
		}
	}()

	start := time.Now()
	for time.Since(start) < 1*time.Second {
		mu.Lock()
		if alice+bob != total {
			fmt.Printf("not equalse bob %d,  alice %d,  total %d\n", bob, alice, total)
		}
		mu.Unlock()
	}
}
